var express = require('express')
var router = express.Router()
const Option = require('../models/option')
const Op = require('sequelize').Op
const Tool = require('../libs/tool')
const { check, validationResult } = require('express-validator/check')
const Interceptor = require('../libs/interceptor')

/* GET actors listing. */
router.get('/', async function(req, res, next) {
  let whereObj = {}
  let orderObj = []
  if (req.query.order && req.query.sortby) {
    orderObj.push([req.query.sortby, req.query.order])
  }
  let interceptor = new Interceptor(req)
  let { offset = 1, limit = 10 } = interceptor.page()
  let result = await Option.findAndCountAll({
    raw: true,
    where: whereObj,
    order: orderObj,
    offset: offset,
    limit: limit
  })
  return res.json({
    code: 0,
    msg: '',
    items: result.rows,
    total: result.count
  })
})

router.get('/menus', async function(req, res, next) {
  return res.json({
    code: 0,
    msg: ''
  })
})

let dbValidator = [
  check('voteId').not().isEmpty().withMessage('投票不能为空'),
  check('optionName').not().isEmpty().withMessage('选项名称不能为空'),
  check('description').not().isEmpty().withMessage('选项简介不能为空')
]
let createValidator = Object.assign([], dbValidator)
router.post('/', createValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  console.log(req.body)

  try {
    let option = await Option.create({
      voteId: req.body.voteId,
      optionName: req.body.optionName,
      description: req.body.description,
      status: req.body.status,
      createdAt: Date.now(),
      updatedAt: Date.now()
    })
    return res.json({
      code: 0,
      msg: '',
      option
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

let updateValidator = Object.assign([], dbValidator)
updateValidator.push(check('optionId').not().isEmpty().withMessage('ID不能为空'))
router.put('/:optionId', updateValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let option = await Option.findByPk(req.params.optionId)
  if (!option) {
    return res.status(404).json({
      code: 404,
      msg: '未找到该数据'
    })
  }
  try {
    let updateData = {
      voteId: req.body.voteId,
      optionName: req.body.optionName,
      description: req.body.description,
      status: req.body.status,
      updatedAt: Date.now()
    }
    let affectedRows = await Option.update(updateData, {
      where: {
        optionId: req.params.optionId
      }
    })
    return res.json({
      code: 0,
      msg: '',
      affectedRows: affectedRows[0]
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

let deleteValidator = [check('optionIds').not().isEmpty().withMessage('ID不能为空')]
router.delete('/:optionIds', deleteValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let optionIds = req.params.optionIds.split(',')
  let options = await Option.findAndCountAll({
    where: {
      optionId: {
        [Op.in]: optionIds
      }
    }
  })
  if (options.count !== optionIds.length) {
    return res.status(404).json({
      code: 404,
      msg: '未找到匹配的数据'
    })
  }
  let inUse = []
  if (inUse.count > 0 && inUse.rows[0]['res_count'] > 0) {
    return res.status(500).json({
      code: 500,
      msg: '选项被其它数据使用'
    })
  }
  try {
    let destroyedRows = await Option.destroy({
      where: {
        optionId: {
          [Op.in]: optionIds
        }
      }
    })
    return res.json({
      code: 0,
      msg: '',
      destroyedRows: destroyedRows
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

module.exports = router
